<template>
  <div v-loading="loading" class="common-chart">
    <div class="chart-header">
      <span>专业分布</span>
      <el-button v-if="currentCategory" size="small" type="primary" @click="handleBack">返回</el-button>
    </div>
    <CommonChart :options="chartOptions" height="calc(100% - 40px)" @my-click="handleClick" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, nextTick, watch } from "vue"
import type { EChartsOption } from "echarts"
import { CommonChart } from "@/components"
import { getDistributionDataApi, getMajorCategoriesApi } from "@/interface"
import "echarts-wordcloud"

const props = defineProps({
  currentMajor: { type: String, default: "" },
  initialCategory: { type: String, default: "" },
  initialSubCategory: { type: String, default: "" }
})
const emits = defineEmits(["update:currentMajor"])

const currentMajor = computed({
  get: () => props.currentMajor,
  set: val => {
    emits("update:currentMajor", val)
  }
})

const loading = ref(false)
const currentCategory = ref<string>("")
const currentSubCategory = ref<string>("")
const distributionData = ref<Record<string, any>[]>([])
const subCategoriesData = ref<Record<string, any>[]>([])
const thirdLevelData = ref<Record<string, any>[]>([])
const categoryData = ref<any>(null)

const chartOptions = computed<EChartsOption>(() => {
  let data: Record<string, any>[] = []
  if (currentSubCategory.value) {
    data = thirdLevelData.value
  } else if (currentCategory.value) {
    data = subCategoriesData.value
  } else {
    data = distributionData.value
  }

  if (!data || data.length === 0) return {}

  return {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)"
    },
    series: [
      {
        type: "pie",
        radius: "50%",
        center: ["50%", "50%"],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ],
    grid: {
      containLabel: true
    }
  }
})

const getDistributionData = () => {
  loading.value = true
  getDistributionDataApi()
    .then((res: any) => {
      distributionData.value = res.data
    })
    .finally(() => {
      loading.value = false
    })
}

const getSubCategoriesData = async (category: string) => {
  loading.value = true
  try {
    const res = await getMajorCategoriesApi(category)
    console.log(res)
    const response: any = res
    if (response.success && response.data.subCategories) {
      // 保存完整的分类数据
      categoryData.value = response.data

      // 添加数据验证和日志
      console.log("获取到的子分类数据:", response.data.subCategories)

      // 确保数据格式正确
      const formattedData = response.data.subCategories
        .map((item: any) => ({
          name: item.name,
          value: item.value || 0
        }))
        .filter((item: any) => item.value > 0)

      console.log("格式化后的数据:", formattedData)

      if (formattedData.length > 0) {
        // 先清空当前数据
        subCategoriesData.value = []
        thirdLevelData.value = []
        // 等待下一个 tick
        await nextTick()
        // 更新数据
        subCategoriesData.value = formattedData
        currentCategory.value = category
        currentSubCategory.value = ""
      } else {
        console.warn("没有有效的子分类数据")
      }
    } else {
      console.warn("API返回数据格式不正确:", response)
    }
  } catch (error) {
    console.error("获取子分类数据失败:", error)
  } finally {
    loading.value = false
  }
}

const handleClick = (params: any) => {
  if (currentSubCategory.value) {
    // 如果当前在三级分类视图，点击时更新选中的专业
    currentMajor.value = params.name
  } else if (currentCategory.value) {
    // 如果当前在二级分类视图，点击时进入三级分类视图
    const subCategory = categoryData.value.subCategories.find((item: any) => item.name === params.name)
    if (subCategory && subCategory.children) {
      const formattedData = subCategory.children
        .map((item: any) => ({
          name: item.name,
          value: item.value || 0
        }))
        .filter((item: any) => item.value > 0)

      thirdLevelData.value = formattedData
      currentSubCategory.value = params.name
    }
  } else {
    // 如果当前在总览视图，点击时进入二级分类视图
    getSubCategoriesData(params.name)
  }
}

const handleBack = () => {
  if (currentSubCategory.value) {
    // 如果当前在三级分类视图，返回到二级分类视图
    currentSubCategory.value = ""
    thirdLevelData.value = []
  } else if (currentCategory.value) {
    // 如果当前在二级分类视图，返回到总览视图
    currentCategory.value = ""
    subCategoriesData.value = []
    categoryData.value = null
  }
}

// 监听一级分类变化
watch(
  () => props.initialCategory,
  async newCategory => {
    console.log("一级分类变化:", newCategory)
    if (newCategory && newCategory !== currentCategory.value) {
      await getSubCategoriesData(newCategory)
    }
  },
  { immediate: true }
)

// 监听二级分类变化
watch(
  () => props.initialSubCategory,
  async newSubCategory => {
    console.log("二级分类变化:", newSubCategory)
    if (newSubCategory && newSubCategory !== currentSubCategory.value) {
      // 如果没有当前分类数据，先获取
      if (!categoryData.value) {
        await getSubCategoriesData(props.initialCategory || currentCategory.value)
      }

      const subCategory = categoryData.value?.subCategories.find((item: any) => item.name === newSubCategory)
      if (subCategory) {
        if (subCategory.children && subCategory.children.length > 0) {
          // 如果有三级分类，显示三级分类数据
          const formattedData = subCategory.children
            .map((item: any) => ({
              name: item.name,
              value: item.value || 0
            }))
            .filter((item: any) => item.value > 0)

          thirdLevelData.value = formattedData
          currentSubCategory.value = newSubCategory
        } else {
          // 如果没有三级分类，直接更新选中的专业
          currentMajor.value = newSubCategory
        }
      }
    }
  },
  { immediate: true }
)

onMounted(() => {
  getDistributionData()
})
</script>

<style scoped>
.common-chart {
  width: 100%;
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
</style>
